<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片列表 -->
    <el-card>
      <!-- 按钮项 -->
      <el-row id="row"
        ><el-button type="primary" @click="addRolesDialogFormVisible = true"
          >添加角色</el-button
        ></el-row
      >
      <el-table :data="rolesList" border stripe>
        <!-- 展开项 -->
        <!-- 对应列的类型。如果设置了 selection 则显示多选框；如果设置了 index 则显示该行的索引（从 1 开始计算）；如果设置了 expand 则显示为一个可展开的按钮 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', indexs === 0 ? 'dbtop' : '', 'vcenter']"
              v-for="(value, indexs) in scope.row.children"
              :key="value.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  :disable-transitions="false"
                  @close="removeid(scope.row, value.id)"
                  >{{ value.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <!-- 渲染二级权限 -->
                <el-row
                  v-for="(value2, indexs2) in value.children"
                  :key="value2.id"
                  :class="[indexs2 === 0 ? '' : 'dbtop', 'vcenter']"
                >
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      :disable-transitions="false"
                      @close="removeid(scope.row, value2.id)"
                      >{{ value2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="12">
                    <el-tag
                      type="warning"
                      v-for="value3 in value2.children"
                      :key="value3.id"
                      closable
                      :disable-transitions="false"
                      @close="removeid(scope.row, value3.id)"
                      >{{ value3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引项 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="200"
        ></el-table-column>
        <el-table-column prop="#" label="操作" width="500">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editRolesDialog(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="rolesDelete(scope.row.id)"
              >
                删除
              </el-button>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRightsDialogView(scope.row)"
              >
                分配权限
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogFormVisible">
      <el-form :model="rolesForm" :rules="addRolesver">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName" clearable required></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="rolesForm.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesDialogFormVisible">
      <el-form :model="rolesForm" :rules="addRolesver">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName" clearable required></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="rolesForm.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialog">
      <el-tree
      ref="rightRef"
        :data="rightsTreedata"
        default-expand-all
        show-checkbox
        :props="defaultProps"
        node-key="id"
        :default-checked-keys="setRightsKeys"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="colsesetRightsDialog">取 消</el-button>
        <el-button type="primary" @click="suesssetRightsDialog()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
/*eslint-disable*/
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 角色表单数据
      rolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 角色表单数据对比
      rolesFormcopy: {
        roleName: "",
        roleDesc: "",
      },
      rolesId: -1,
      // 控制添加角色对话框显示
      addRolesDialogFormVisible: false,
      editRolesDialogFormVisible: false,
      setRightsDialog: false,
      // 表单验证
      addRolesver: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
      },
      // 权限列表树
      rightsTreedata: [],
      // 权限列表树数据绑定
      defaultProps: {
        children: "children",
        label: "authName",
      },
      // 权限列表树默认勾选
      setRightsKeys:[]
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
      this.rolesForm.roleName = "";
      this.rolesForm.roleDesc = "";
    },
    // 添加角色
    async addRoles() {
      const { data: res } = await this.$http.post("/roles", this.rolesForm);
      this.getRolesList();
      this.addRolesDialogFormVisible = false;
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg);
      }
      return this.$message.success(res.meta.msg);
    },
    // 编辑角色弹窗
    editRolesDialog(row) {
      this.editRolesDialogFormVisible = true;
      this.rolesForm.roleName = row.roleName;
      this.rolesForm.roleDesc = row.roleDesc;
      this.rolesFormcopy.roleName = row.roleName;
      this.rolesFormcopy.roleDesc = row.roleDesc;
      this.rolesId = row.id;
    },
    // // 编辑角色数据
    async editRoles() {
      // 如果数据未改变不执行
      if (
        this.rolesFormcopy.roleName == this.rolesForm.roleName &&
        this.rolesFormcopy.roleDesc == this.rolesForm.roleDesc
      ) {
        return this.$message.error("数据为改变");
      }
      // return this.$message.error('数据未改变')

      const { data: res } = await this.$http.put(
        "/roles/" + this.rolesId,
        this.rolesForm
      );
      this.editRolesDialogFormVisible = false;
      this.getRolesList();
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      return this.$message.success("修改成功");
    },
    // 删除角色
    async rolesDelete(id) {
      const deletedata = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        // .then(() => {
        //   this.$http.delete("/roles/" + id)
        //   this.getRolesList()

        //   this.$message.success("删除成功")
        // })
        .catch(() => {});
      if (deletedata === "confirm") {
        const { data: res } = await this.$http.delete("/roles/" + id);
        if (res.meta.status === 200) {
          this.getRolesList();
          return this.$message.success("删除成功");
        } else {
          return this.$message.error("未知错误");
        }
      }
    },
    // 关闭标签
    async removeid(role, rightId) {
      const deletedata = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (deletedata === "confirm") {
        const { data: res } = await this.$http.delete(
          "/roles/" + role.id + "/rights/" + rightId
        );
        if (res.meta.status !== 200) {
          return this.$message.error("删除权限失败");
        }
        role.children = res.data;
        return this.$message.success(res.meta.msg);
      }
    },
    // 递归函数 获取已有权限id
    getLeafKeys(node,arr){
// 如果node下没有children则认为是第三级权限
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getLeafKeys(element,arr)
      });
    },
    // 分配权限对话框
    async setRightsDialogView(row) {
      // 获取权限树
      this.rolesId = row.id
      const { data: res } = await this.$http.get("rights/tree");
      // 获取角色对应权限
      this.getLeafKeys(row,this.setRightsKeys)
      this.rightsTreedata = res.data;
      this.setRightsDialog = true;
      
    },
    // 取消按钮，清空setRightsKeys
    colsesetRightsDialog(){
      this.setRightsKeys=[]
      this.setRightsDialog=false
      this.rolesId = -1

    },
    // q确定按钮
    async suesssetRightsDialog(){
      const keys = [
        this.$refs.rightRef.getCheckedKeys(),
        this.$refs.rightRef.getHalfCheckedKeys()
        ]
      const keysStr = keys.join(',')
      const {data:res} = await this.$http.post('/roles/'+ this.rolesId +'/rights', {rids:keysStr})
      if(res.meta.status !==200){
        return this.$message.error("出现未知错误")
      }
      this.rolesId = -1
      this.getRolesList()
      this.setRightsDialog =false
      this.setRightsKeys=[]
      return this.$message.success("权限更新成功")
    },
 
  },
};
</script>

<style lang="less" scoped>
#row {
  float: left;
  margin-bottom: 20px;
}
.el-col {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 5px;
  align-items: center;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
